package com.haoshuang.zhouzhoubang.ui.activity

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivitySubmitAcceptanceBinding
import com.haoshuang.zhouzhoubang.model.bean.Image2Bean
import com.haoshuang.zhouzhoubang.model.bean.LogBen
import com.haoshuang.zhouzhoubang.model.bean.OrderBean5
import com.haoshuang.zhouzhoubang.model.bean.OrderDetail2Bean
import com.haoshuang.zhouzhoubang.ui.adapter.EwAdapter
import com.haoshuang.zhouzhoubang.ui.adapter.ImageAdapter23
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowUploadExampleDialog
import com.haoshuang.zhouzhoubang.ui.dialog.UploadWriteOffCodeDialog
import com.haoshuang.zhouzhoubang.ui.vm.SubmitAcceptanceViewModel
import com.haoshuang.zhouzhoubang.utils.ChooseMediaUtils
import com.haoshuang.zhouzhoubang.utils.MediaPlayUtils
import com.haoshuang.zhouzhoubang.utils.OSSUploadUtils
import com.haoshuang.zhouzhoubang.widget.UploadFileBean
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible
import com.mufeng.libs.utils.view.visibleOrGone


/**
 *  提交验收界面
 */
class SubmitAcceptanceActivity :
    BaseVMActivity<SubmitAcceptanceViewModel, ActivitySubmitAcceptanceBinding>() {


    private var logBean: LogBen? = null

    var adapter8: ImageAdapter23? = null
    var list8 = arrayListOf<Image2Bean>()
    var type9 = 0

    private lateinit var ewAdapter: EwAdapter
    var ids = 0
    var list1 = arrayListOf<OrderDetail2Bean.CostList>()
    var gson = Gson()
    private var orderBean5: OrderBean5? = null
    private var is_rework = false

    /**
     * 服务中的图片和视频列表
     */
    private val inServiceMediaList = arrayListOf<UploadFileBean>()

    private var orderDetailBean: OrderDetail2Bean? = null

    override fun initView(savedInstanceState: Bundle?) {
        is_rework = intent.getBooleanExtra("is_rework", false)
        adapter8 = ImageAdapter23(list8)
        binding.rvInService1.layoutManager = GridLayoutManager(this, 4)
        binding.rvInService1.adapter = adapter8
        ids = intent.getIntExtra("ids", 0)
        binding.tvUploadExample.clickWithTrigger {
            // 查看上传示例
            // 后期需要先请求接口
            XPopup.Builder(mActivity)
                .asCustom(ShowUploadExampleDialog(context = mActivity, ids.toString(), 3))
                .show()
        }
        vm.getData2("id" to ids)
        val json = intent.getStringExtra("json").toString()
        if (json.isNullOrBlank() || json == "null") {
            binding.tvEw.gone()
            binding.rvE.gone()
        } else {
            try {
                binding.tvEw.visible()
                binding.rvE.visible()
                list1 = gson.fromJson(
                    json,
                    object : TypeToken<ArrayList<OrderDetail2Bean.CostList>>() {}.getType()
                )
                ewAdapter = EwAdapter(list1)
                binding.rvE.layoutManager = LinearLayoutManager(this@SubmitAcceptanceActivity)
                binding.rvE.adapter = ewAdapter
            } catch (e: Exception) {
                binding.tvEw.gone()
                binding.rvE.gone()
            }

        }
        binding.tXz.clickWithTrigger {
            if (type9 == 0) {
                type9 = 1
                binding.tXz.setImageResource(R.mipmap.icon_xl2)
                binding.ivImage.visible()
            } else {
                type9 = 0
                binding.ivImage.gone()
                binding.tXz.setImageResource(R.mipmap.icon_xl)
            }
        }
        // 点击查看奖励
        binding.ivUploadReward.clickWithTrigger {
            XPopup.Builder(this)
                .asCustom(
                    ConfirmDialog(
                        context = this,
                        title = "上传视频奖励",
                        content = "需上传服务前服务中视频有${logBean?.upload_video_award ?: "0"}元上传奖励",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        onCancel = {},
                        onConfirm = {})
                )
                .show()
        }
        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            appBar.tvTitle.text = "提交验收"
            appBar.tvRight.clickWithTrigger {
                showUploadWriteOffCodeDialog()
            }

            btnSubmitAcceptance.setOnClickListener {
                XPopup.Builder(mActivity)
                    .asCustom(
                        ConfirmDialog(
                            context = mActivity,
                            title = "温馨提示",
                            content = "提交验收之前, 请师傅自验自检",
                            cancelStr = "去检查",
                            confirmStr = "继续提交",
                            isHideCancel = false,
                            onCancel = {

                            },
                            onConfirm = {
                                val imageListAfterService =
                                    rvAfterService.getMediaList().filter { !it.isVideo }

                                /*  if (imageListAfterService.isEmpty()) {
                                      toast("请上传服务后图片")
                                      return@ConfirmDialog
                                  }*/
//                            if (imageListAfterService.size < 4){
                                if (orderBean5?.image_hou_show != 0) {
                                    if (imageListAfterService.size < orderBean5?.image_hou_count!!) {
//                                toast("最少4张")
                                        toast("服务后照片最少" + orderBean5?.image_hou_count + "张")
                                        return@ConfirmDialog
                                    }
                                }
                                commit()

                            })
                    )
                    .show()


            }
        }
    }

    override fun initData() {
        vm.getData5("id" to ids)

        // 获取订单详情
        vm.getOrderDetail("id" to ids)
    }

    override fun startObserve() {

        vm.getOrderDetailData.observeState(this) {
            onSuccess {
                orderDetailBean = it

                if (orderDetailBean?.is_cart_order == 1) {
                    binding?.layoutServiceItem?.visibility = android.view.View.VISIBLE
                    binding?.layoutServiceItemOld?.visibility = android.view.View.GONE

                    var serviceItemAdapter: ServiceItemWithImgAdapter?
                    if (orderDetailBean?.order_goods?.size!! > 2) {
                        serviceItemAdapter =
                            ServiceItemWithImgAdapter(orderDetailBean?.order_goods!!.subList(0, 2))
                        binding?.layoutLookmore?.visibility = android.view.View.VISIBLE
                    } else {
                        serviceItemAdapter = ServiceItemWithImgAdapter(orderDetailBean?.order_goods!!)
                        binding?.layoutLookmore?.visibility = android.view.View.GONE
                    }
                    binding?.recyclerViewSeriviceItem?.layoutManager =
                        androidx.recyclerview.widget.LinearLayoutManager(
                            this@SubmitAcceptanceActivity,
                            androidx.recyclerview.widget.LinearLayoutManager.VERTICAL, false
                        )
                    binding?.recyclerViewSeriviceItem?.adapter = serviceItemAdapter
                    binding?.layoutLookmore?.click {
                        serviceItemAdapter.submitList(orderDetailBean?.order_goods!!)
                        binding?.layoutLookmore?.visibility = android.view.View.GONE
                    }

                } else {
                    binding?.layoutServiceItem?.visibility = android.view.View.GONE
                    binding?.layoutServiceItemOld?.visibility = android.view.View.VISIBLE
                }


            }
        }

        vm.uploadWriteOffCodeData.observeState(this) {
            onLoading { }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("核销码上传成功, 等待核销")
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                logBean = it
                if (it != null) {
                    list8.clear()

                    if (!it.before_service_img.isNullOrBlank()) {
                        var arr = it.before_service_img.split(",")
                        for (b in arr) {
                            list8.add(Image2Bean(b, 0))
                        }
                        if (!it.before_service_video.isNullOrBlank()) {
                            list8.add(Image2Bean(it.before_service_video, 1))
                        }
                    }
                    adapter8?.notifyDataSetChanged()
                    inServiceMediaList.clear()
                    if (!it.service_img.isNullOrBlank()) {
                        var arr = it.service_img.split(",").filter { it.isNotEmpty() }
                        val list = arr.map { UploadFileBean(null, it, 0, false, 2) }
                        inServiceMediaList.addAll(list)
                    }
                    if (!it.service_video.isNullOrBlank()) {
                        inServiceMediaList.add(UploadFileBean(null, it.service_video, 0, true, 2))
                    }

                    binding.rvInService.setMediaList(inServiceMediaList)

                    binding.appBar.tvRight.visibleOrGone(it.is_write_off == 1 && it.write_off_image.isNullOrEmpty())
                    binding.appBar.tvRight.text = "上传核销码"
                    if (it.is_write_off == 1 && it.write_off_image.isNullOrEmpty()) {
                        showUploadWriteOffCodeDialog()
                    }
                }
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                toast("提交成功")
                MediaPlayUtils.playSubmitAcceptanceSuccess()
                if (!is_rework) {
                    LiveEventBus.get<Boolean>("Sxx").post(true)
                } else {
                    setResult(200)
                }
                finish()
            }
        }

        vm.getData5.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                orderBean5 = it
                binding.apply {
                    ivHead.load(it?.image)
                    ivImage.load(it?.service_con_image, R.mipmap.default_image)
                    tvName.text = it?.store_name
                    tvMaij.text = it?.suk_unique
                    tvMark.setText(it?.remark)
                    tvMark1.setText(it?.remark)

                    binding.tvInService.text =
                        "服务中照片（至少" + orderBean5?.image_zhong_count + "张）"
                    binding.tvAfterService.text =
                        "服务后照片（至少" + orderBean5?.image_hou_count + "张）"


                    if (orderBean5?.image_qian_show == 0) {
                        binding?.layoutFuwuqian?.visibility = View.GONE
                    } else {
                        binding?.layoutFuwuqian?.visibility = View.VISIBLE
                    }

                    if (orderBean5?.image_zhong_show == 0) {
                        binding?.layoutFuwuzhong?.visibility = View.GONE
                    } else {
                        binding?.layoutFuwuzhong?.visibility = View.VISIBLE
                    }
                    if (orderBean5?.image_hou_show == 0) {
                        binding?.layoutFuwuhou?.visibility = View.GONE
                    } else {
                        binding?.layoutFuwuhou?.visibility = View.VISIBLE
                    }

                }
            }
        }
    }

    /**
     * 上传核销码
     */
    private fun showUploadWriteOffCodeDialog() {
        XPopup.Builder(this)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asCustom(
                UploadWriteOffCodeDialog(
                    this,
                    "您未上传核销码请上传后，\n再提交验收",
                    isHideCancel = true
                ) {
                    uploadWriteOffCodeImage()
                })
            .show()
    }

    private fun uploadWriteOffCodeImage() {
        ChooseMediaUtils(mActivity).selectSingleImageWithCamera(object :
            OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                if (result != null && result.size > 0) {
                    OSSUploadUtils.uploadFile("app/upload", result.first().realPath) {
                        start { showLoading() }
                        error { clientException, serviceException ->
                            dismissLoading()
                            toast("图片上传失败")
                        }
                        success {
                            dismissLoading()
                            vm.uploadWriteOffCode(ids.toString(), it)
                        }
                    }
                }
            }

            override fun onCancel() {

            }
        })
    }

    var remark = ""
    var service_img = ""
    var service_video = ""
    var after_service_img = ""
    var after_service_video = ""
    private fun commit() {
        val imageListAfterService = binding.rvAfterService.getMediaList().filter { !it.isVideo }
        val videoListAfterService = binding.rvAfterService.getMediaList().filter { it.isVideo }
        val imageListInService = binding.rvInService.getMediaList().filter { !it.isVideo }
        val videoListInService = binding.rvInService.getMediaList().filter { it.isVideo }

        // 服务后视频地址
        after_service_video = videoListAfterService.firstOrNull()?.url ?: ""
        // 服务后图片地址
        after_service_img = imageListAfterService.joinToString(",") { it.url ?: "" }
        // 服务中的视频地址
        service_video = videoListInService.firstOrNull()?.url ?: ""
        // 服务中的图片地址
        service_img = imageListInService.joinToString(",") { it.url.toString() }

        val params = mutableListOf<Pair<String, Any?>>()
        params.add("id" to ids)
        params.add("remark" to remark)
        if (after_service_video.isNotEmpty()) {
            params.add("after_service_video" to after_service_video)
        }
        if (after_service_img.isNotEmpty()) {
            params.add("after_service_img" to after_service_img)
        }
        if (service_video.isNotEmpty()) {
            params.add("service_video" to service_video)
        }
        if (service_img.isNotEmpty()) {
            params.add("service_img" to service_img)
        }
        vm.getData(*params.toTypedArray())

    }

}